<?php
class Upload {
	private $size;
	private $type;
	public $error;
//	构造函数    传两个参数为null   在里面判断
	public function __construct($size = NULL, $type = NULL) {
		$this -> size = is_null($size) ? 2000000 : $size;
		$this -> type = is_null($type) ? array('jpg', 'png', 'jpeg', 'gif') : $type;
	}

	public function up() {
		//		重组数组
		$arr = $this -> resetArr();
		//		筛选
		foreach ($arr as $v) {
			if (!$this -> filter($v)) {
				//				空数组也是假
				return array();
			}
		}
//		上传   声明一个空数组
		$dastArr = array();
		foreach ($arr as $v) {
//			把上传好的方法压入空数组
			$destArr[] = $this -> move($v);
		}
		return $destArr;
	}
//移动上传方法
	private function move($v) {
		$path = './upload/' . date('ymd');
		is_dir($path) || mkdir($path, 0777, true);
		$type = strrchr($v['name'], '.');
		$filename = time() . mt_rand(0, 999999) . $type;
		$dest = $path . '/' . $filename;
		move_uploaded_file($v['tmp_name'], $dest);
		return $dest;
	}

	//	筛选方法
	private function filter($v) {
		//		获得文件类型
		$type = ltrim(strrchr($v['name'], '.'), '.');
		switch (true) {
			case $v['error'] == 4 :
				$this -> error = '没有文件被上传';
				return false;
			case $v['error'] == 1 :
				$this -> error = '大小超过限制值';
				return false;
			case $v['error'] == 2 :
				$this -> error = '超过指定的值';
				return false;
			case $v['error'] == 3 :
				$this -> error = '只有部分被上传';
				return false;
			case !is_uploaded_file($v['tmp_name']) :
				$this -> error = '不是一个合法文件';
				return false;
			case $v['size']>$this ->size :
				$this -> error = '文件超过配置大小';
				return false;
			case !in_array($type, $this->type) :
				$this -> error = '上传文件类型不允许';
				return false;
			default :
				return true;
		}
	}

	//重组数组
	private function resetArr() {
		$arr = array();
		foreach ($_FILES as $v) {
			if (is_array($v['name'])) {
				foreach ($v['name'] as $key => $value) {
					$arr[] = array('name' => $value, 'type' => $v['type'][$key], 'tmp_name' => $v['tmp_name'][$key], 'error' => $v['error'][$key], 'size' => $v['size'][$key]);
				}
			} else {
				$arr[] = $v;
			}

		}
		return $arr;
	}

}
?>